package org.n.shop.util;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import io.minio.errors.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.n.shop.config.MinioConfig;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.Objects;

@Component
@Slf4j
@AllArgsConstructor
public class MinioUtil {
    private MinioConfig minioConfig;
    private MinioClient minioClient;

    public String putObject(String catalog, MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String fileName = getFileName(Objects.requireNonNull(originalFilename));
        String objectName = filePath(catalog, fileName);
        try (InputStream stream = file.getInputStream();) {
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(minioConfig.getBucketName())
                            .object(objectName)
                            .contentType(file.getContentType())
                            .stream(stream, stream.available(), -1)
                            .build()
            );
        } catch (Exception e) {
            log.error("文件流上传错误!", e);
            throw new RuntimeException("文件上传失败！");
        }
        return objectName;
    }

    public boolean removeObject(String fileName) {
        try {
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(minioConfig.getBucketName()).object(fileName).build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public String getObject(String fileName) {
        return minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + fileName;
    }

    private String getFileName(String objectName) {
        int lastIndexOf = objectName.lastIndexOf(".");
        if (lastIndexOf == -1) {
            return objectName + LocalDateTime.now();
        } else {
            String prefix = objectName.substring(0, objectName.lastIndexOf('.'));
            String suffix = objectName.substring(objectName.lastIndexOf('.') + 1);

            return prefix + LocalDateTime.now() + "." + suffix;
        }
    }

    private String filePath(String catalog, String fileName) {
        return "/" + catalog + "/" + fileName;
    }
}
